package bjtu.student.portrait.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.util.IoUtils;
import org.openapitools.jackson.nullable.JsonNullable;

import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URLConnection;

public class NullableURIImageConverter implements Converter<JsonNullable<URI>> {
    public static int urlConnectTimeout = 1000;
    public static int urlReadTimeout = 5000;

    @Override
    public Class<?> supportJavaTypeKey() {
        return JsonNullable.class;
    }

//        @Override
//        public JsonNullable<URI> convertToJavaData(com.alibaba.excel.converters.Converter.ConverterContext context) {
//            return JsonNullable.of(URI.create(context.getReadCellData().getStringValue()));
//        }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<JsonNullable<URI>> context) throws IOException {
        URI uri = context.getValue().get();
        if (uri == null) {
            return new WriteCellData<>("");
        }
        InputStream inputStream = null;
        try {
            URLConnection urlConnection = uri.toURL().openConnection();
            urlConnection.setConnectTimeout(urlConnectTimeout);
            urlConnection.setReadTimeout(urlReadTimeout);
            inputStream = urlConnection.getInputStream();
            byte[] bytes = IoUtils.toByteArray(inputStream);
            return new WriteCellData<>(bytes);
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
}
